package com.dlc.shop.platform.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.dto.BrandShopDTO;
import com.dlc.shop.bean.dto.BrandSigningDTO;
import com.dlc.shop.bean.model.Brand;
import com.dlc.shop.bean.vo.BrandShopVO;
import com.dlc.shop.bean.vo.BrandSigningVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.jky.common.foreign.service.ForeignProbranCategoryService;
import com.dlc.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 品牌管理
 *
 * @author lgh
 */
@RestController
@RequestMapping("/platform/brand")
@Tag(name = "品牌相关接口")
@AllArgsConstructor
public class BrandController {

    private final BrandService brandService;
    private final BrandShopService brandShopService;
    private final CategoryService categoryService;
    private final ProductService productService;
    private final CategoryBrandService categoryBrandService;
    private final ForeignProbranCategoryService foreignProbranCategoryService;

    @GetMapping("/page")
    @Operation(summary = "分页获取品牌信息列表" , description = "分页获取品牌信息列表")
    public ServerResponseEntity<IPage<Brand>> page( PageParam<Brand> pageDTO, Brand brandDTO) {
        brandDTO.setShopId(Constant.PLATFORM_SHOP_ID);
        IPage<Brand> brandPage = brandService.page(pageDTO, brandDTO);
        return ServerResponseEntity.success(brandPage);
    }

    @GetMapping("/list")
    @Operation(summary = "获取平台品牌列表（不分页）" , description = "获取平台品牌列表（不分页）")
    public ServerResponseEntity<List<Brand>> list(Brand brand) {
        brand.setShopId(Constant.PLATFORM_SHOP_ID);
        List<Brand> brandList = brandService.listByParams(brand);
        return ServerResponseEntity.success(brandList);
    }

    @GetMapping("/info/{brandId}")
    @Operation(summary = "获取品牌信息" , description = "根据brandId获取品牌信息")
    @Parameter(name = "brandId", description = "品牌id" )
    public ServerResponseEntity<Brand> getByBrandId(@PathVariable Long brandId) {
        Brand brand = brandService.getInfo(brandId);
        categoryService.getPathNames(brand.getCategories());

        return ServerResponseEntity.success(brand);
    }

    @PostMapping
    @Operation(summary = "保存品牌信息" , description = "保存品牌信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody Brand brand) {
        brand.setShopId(Constant.PLATFORM_SHOP_ID);
        brandService.saveBrand(brand);
        foreignProbranCategoryService.plaSaveBrand(brand);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新品牌信息" , description = "更新品牌信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody Brand brand) {
        if (Objects.isNull(brand.getCategoryIds())) {
            brand.setCategoryIds(new ArrayList<>());
        }
        List<Long> prodIds = brandService.updateBrand(brand);
        // 清除缓存
        List<Long> categoryIds = categoryBrandService.getCategoryIdBrandId(brand.getBrandId());
        categoryIds.addAll(brand.getCategoryIds());
        productService.removeProductCacheByProdIds(prodIds);
        foreignProbranCategoryService.plaUpdateBrand(brand);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除品牌信息" , description = "根据品牌信息id删除品牌信息")
    @Parameter(name = "brandId", description = "品牌id" )
    public ServerResponseEntity<Void> delete(@RequestParam Long brandId) {
        List<Long> prodIds = brandService.deleteById(brandId);
        productService.removeProductCacheByProdIds(prodIds);
        foreignProbranCategoryService.plaDeleteBrand(brandId);
        return ServerResponseEntity.success();
    }

    @PutMapping(value = "/updateBrandStatus")
    @Operation(summary = "更新品牌状态（启用或禁用）" , description = "更新品牌状态（启用或禁用）")
    public ServerResponseEntity<Void> updateBrandStatus(@RequestBody Brand brand) {
        if (Objects.isNull(brand.getStatus())) {
            throw new YamiShopBindException("状态不能为空");
        }
        if (Objects.isNull(brand.getBrandId())) {
            throw new YamiShopBindException("品牌id不能为空");
        }
        List<Long> prodIds = brandService.updateBrandStatus(brand);
        productService.removeProductCacheByProdIds(prodIds);
        // 清楚缓存
        List<Long> categoryIds = categoryBrandService.getCategoryIdBrandId(brand.getBrandId());
        // 获取当前节点所有父节点的分类ids，以及当前分类节点的父级节点的父级几点的分类ids
        List<Long> parentCategoryIds = categoryService.getParentIdsByCategoryId(categoryIds);
        if (CollUtil.isNotEmpty(parentCategoryIds)) {
            categoryIds.addAll(parentCategoryIds);
        }

        return ServerResponseEntity.success();
    }

    @GetMapping("/listSigningByShopId")
    @Operation(summary = "根据店铺id获取签约的品牌列表" , description = "根据店铺id获取签约的品牌列表")
    @Parameters(value = {
            @Parameter(name = "shopId", description = "店铺id" , required = true),
            @Parameter(name = "status", description = "状态 1:启用, 0:禁用" )
    })
    public ServerResponseEntity<BrandSigningVO> listSigningByShopId(@RequestParam(value = "shopId") Long shopId, @RequestParam(value = "status", required = false) Integer status) {
        BrandSigningVO brandSigningVO = brandShopService.listSigningByShopId(shopId, status);
        return ServerResponseEntity.success(brandSigningVO);
    }

    @GetMapping("/pageSigningByShopId")
    @Operation(summary = "根据店铺id分页获取签约的品牌列表" , description = "根据店铺id分页获取签约的品牌列表")
    public ServerResponseEntity<IPage<BrandShopVO>> pageSigningByShopId(PageParam<BrandShopVO> page, BrandShopDTO brandShop) {
        IPage<BrandShopVO> brandShopPage = brandShopService.pageSigningByShopId(page, brandShop);
        return ServerResponseEntity.success(brandShopPage);
    }

    @PutMapping("/signing")
    @Operation(summary = "根据店铺id更新店铺下的签约品牌" , description = "根据店铺id更新店铺下的签约品牌")
    @Parameter(name = "shopId", description = "店铺id" )
    public ServerResponseEntity<Void> signingBrands(@RequestBody BrandSigningDTO brandSigningDTO, @RequestParam(value = "shopId") Long shopId) {
        brandShopService.signingBrands(brandSigningDTO, shopId, true);
        return ServerResponseEntity.success();
    }

}
